﻿using Atletika.Common;
using Atletika.Data;
using Atletika.Helpers;
using Atletika.Shared.Entities;
using Atletika.Shared.Helpers;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.Resources;
using Windows.ApplicationModel.Resources.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Hub Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=321224

namespace Atletika
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class HubPage : Page
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        public HubPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            Window.Current.Activated += CurrentWindow_Activated;

            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
        }

        

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            if (e.PageState == null || this.RefreshPeriodically())
            {
                await this.RefreshData(true);
            }
        }

        private async void CurrentWindow_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.CodeActivated && this.RefreshPeriodically())
            {
                await this.RefreshData(true);
            }
        }

        private bool RefreshPeriodically()
        {
            int interval = 60 * 30;

            try
            {
                CultureInfo provider = new CultureInfo("sk-SK");
                Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                DateTime lastUpdate = DateTime.ParseExact(localSettings.Values["LastUpdate"].ToString(), "dd.MM.yyyy HH:mm:ss", provider);

                if ((DateTime.Now - lastUpdate).TotalSeconds > interval)
                {
                    return true;
                }
            }
            catch
            { }

            return false;
        }

        private async Task RefreshData(bool manual)
        {
            Exception exception = null;

            this.progressRing.IsActive = true;

            try
            {
                bool download = false;

                #region Get articles

                if (manual || (App.Current as App).Articles == null)
                {
                    (App.Current as App).Articles = await DownloadHelper.GetArticles();
                    download = true;
                }

                this.DefaultViewModel["HomeArticles"] = (App.Current as App).Articles.Where(a => a.CategoryId == 1).Take(18).ToList();
                this.DefaultViewModel["WorldArticles"] = (App.Current as App).Articles.Where(a => a.CategoryId == 2).Take(18).ToList();

                #endregion

                #region Get competitions

                if (manual || (App.Current as App).Competitions == null)
                {
                    (App.Current as App).Competitions = await DownloadHelper.GetCompetitions();
                    download = true;
                }

                this.DefaultViewModel["Competitions"] = (App.Current as App).Competitions.Where(c => c.bResults).OrderByDescending(c => c.DateFrom).Take(18).ToList();

                #endregion

                #region Save last update

                if (download)
                {
                    ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
                    localSettings.Values["LastUpdate"] = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");
                }

                #endregion
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                this.progressRing.IsActive = false;
            }

            if (exception != null)
            {
                await new MessageDialog("Aplikácii sa nepodarilo načítať údaje.", "Slovenská atletika").ShowAsync();
            }
        }

        private async void Refresh_Click(object sender, RoutedEventArgs e)
        {
            if (this.RefreshPeriodically())
            {
                await this.RefreshData(true);
            }
        }

        private void Info_Click(object sender, RoutedEventArgs e)
        {
            string path = "http://www.atletikasvk.sk";
            ConnectionHelper.LaunchUri(path);
        }
        

        #region Selection changed

        // Hub section header click
        void Hub_SectionHeaderClick(object sender, HubSectionHeaderClickEventArgs e)
        {
            if (Convert.ToInt32(e.Section.Tag) == 1)
            {
                HubSection section = e.Section;
                List<Article> articles = (List<Article>)section.DataContext;
                if (articles != null && articles.Count > 0)
                {
                    this.Frame.Navigate(typeof(ArticlesPage), articles[0].CategoryId);
                }
            }
            
            if (Convert.ToInt32(e.Section.Tag) == 2)
            {
                this.Frame.Navigate(typeof(CompetitionsPage));
            }
        }

        // Article selected
        private void ArticleSelected(object sender, ItemClickEventArgs e)
        {
            var article = (Article)e.ClickedItem;
            this.Frame.Navigate(typeof(ArticleDetailPage), article);
        }

        // Competition selected
        private async void CompetitionSelected(object sender, ItemClickEventArgs e)
        {
            var competition = (Competition)e.ClickedItem;

            if (ConnectionHelper.ConnectedToInternet() && competition.bResults)
            {
                // Open results in web browser
                ConnectionHelper.LaunchUri(competition.sResults);
            }
            else
            { 
                await new MessageDialog("Výsledky nie sú dostupné.", "Slovenská atletika").ShowAsync();            
            }
        }

        #endregion

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.RegisterBackgroundTask();
            
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        #region BackgroundTasks

        private const string taskName = "TileUpdater";
        private const string taskEntryPoint = "BackgroundTasks.TileUpdater";

        private async void RegisterBackgroundTask()
        {
            var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
            if (backgroundAccessStatus == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity ||
                backgroundAccessStatus == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity)
            {
                foreach (var task in BackgroundTaskRegistration.AllTasks)
                {
                    if (task.Value.Name == taskName)
                    {
                        task.Value.Unregister(true);
                    }
                }

                BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
                taskBuilder.Name = taskName;
                taskBuilder.TaskEntryPoint = taskEntryPoint;
                taskBuilder.SetTrigger(new TimeTrigger(15, false));
                var registration = taskBuilder.Register();
            }
        }

        #endregion

        
    }
}
